package com.atmilan.quartz.utils.product;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.config.RestTemplateConfig;
import com.atmilan.quartz.model.dto.pure.PureProductResDTO;
import com.atmilan.quartz.model.dto.pure.PureStockResDTO;
import com.atmilan.quartz.model.entity.pure.PureImages;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.xml.sax.InputSource;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class PrueProductUtil {

    @Autowired
    private RestTemplateConfig restTemplateConfig;

    @Value("${pure.url}")
    private String pureUrl;
    @Value("${pure.products}")
    private String pureProducts;
    @Value("${pure.stocks}")
    private String pureStocks;

    /**
     * 获取pure商品列表
     * @return
     */
    public List<PureProductResDTO> getPureProducts() {
        List<PureProductResDTO> pureProductResDTOList = new ArrayList<>();
        try {
            StringBuilder sb = new StringBuilder().append(pureUrl)
                    .append("?").append(pureProducts);
            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);
            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
                String errorMessage = message.getString("error");
                log.info("--------------- 获取pure商品列表异常{} ---------------", errorMessage);
            }
            pureProductResDTOList = JSONObject.parseArray(response.getBody(), PureProductResDTO.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return pureProductResDTOList;
    }

    public static void main(String[] args) {
        String pureUrl ="http://main.puresermoneta.com/service/index.php";
        String pureProducts = "type=products";
        String socket = "type=stocks";
        StringBuilder sb = new StringBuilder().append(pureUrl)
                .append("?").append(pureProducts);
//        ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);
        HttpRequest post = HttpUtil.createPost(sb.toString());
        HttpResponse execute = post.execute();
        String body = execute.body();
        System.out.println();
    }

    /**
     * 获取pure商品库存
     * @return
     */
    public List<PureStockResDTO> getPureStocks() {
        List<PureStockResDTO> pureStockResDTOList = new ArrayList<>();
        try {
            StringBuilder sb = new StringBuilder().append(pureUrl)
                    .append("?").append(pureStocks);
            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);
            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
                String errorMessage = message.getString("error");
                log.info("--------------- 获取pure商品库存异常{} ---------------", errorMessage);
            }
            pureStockResDTOList = JSONObject.parseArray(response.getBody(), PureStockResDTO.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return pureStockResDTOList;
    }

    public List<PureImages> getPureImages() throws Exception {
        List<String> imageIdList = new ArrayList<>();
        List<String> productIdList = new ArrayList<>();
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        ResponseEntity<String> imageResponse = restTemplate.getForEntity("https://puresermoneta.com/api/images/products?ws_key=VGQWAJ785A5EWRIPFYE1IC3QV5PMLLS6", String.class);
        InputSource in = new InputSource(new StringReader(imageResponse.getBody()));
        in.setEncoding("UTF-8");
        SAXReader reader = new SAXReader();
        Document document = reader.read(in);
        Element rootElt = document.getRootElement();
        Element images = rootElt.element("images");
        List<Element> imageList = images.elements();
        imageList.forEach(e->imageIdList.add(e.attribute("id").getValue()));

        ResponseEntity<String> productResponse = restTemplate.getForEntity("https://puresermoneta.com/api/products?ws_key=VGQWAJ785A5EWRIPFYE1IC3QV5PMLLS6", String.class);
        InputSource productIn = new InputSource(new StringReader(productResponse.getBody()));
        in.setEncoding("UTF-8");
        Document productDocument = reader.read(productIn);
        Element productElt = productDocument.getRootElement();
        Element products = productElt.element("products");
        List<Element> productList = products.elements();
        productList.forEach(e->productIdList.add(e.attribute("id").getValue()));

        imageIdList.retainAll(productIdList);
        List<PureImages> pureImageList = new ArrayList<>();
        for (String id : imageIdList) {
            ResponseEntity<String> product = restTemplate.getForEntity("https://puresermoneta.com/api/products/"+id+"?ws_key=VGQWAJ785A5EWRIPFYE1IC3QV5PMLLS6", String.class);
            Document productRead = reader.read(new InputSource(new StringReader(product.getBody())));
            Element productElement = productRead.getRootElement().element("product");
            //ean13
            String ean13 = productElement.element("ean13").getText();
            //images
            List<Element> imagesElement = productElement.element("associations").element("images").elements();
            List<String> PicList = imagesElement.stream().map(e -> e.attribute("href").getValue()+"?ws_key=VGQWAJ785A5EWRIPFYE1IC3QV5PMLLS6").collect(Collectors.toList());
            JSONArray gallery = JSONArray.parseArray(JSON.toJSONString(PicList));
            PureImages pureImages = new PureImages();
            pureImages.setProductId(id).setEan13(ean13).setImages(gallery.toJSONString());
            pureImageList.add(pureImages);
            //combinations
            List<Element> combinations = productElement.element("associations").element("combinations").elements();
            for (Element combination : combinations) {
                ResponseEntity<String> combinationRes = restTemplate.getForEntity(combination.attribute("href").getValue()+"?ws_key=VGQWAJ785A5EWRIPFYE1IC3QV5PMLLS6", String.class);
                Document combinationRead = reader.read(new InputSource(new StringReader(combinationRes.getBody())));
                Element combinationElement = combinationRead.getRootElement().element("combination");
                String skuEan13 = combinationElement.element("ean13").getText();
                List<Element> skuImages = combinationElement.element("associations").element("images").elements();
                if(null != skuImages && skuImages.size() > 0){
                    List<String> skuPicList = skuImages.stream().map(e -> e.attribute("href").getValue()+"?ws_key=VGQWAJ785A5EWRIPFYE1IC3QV5PMLLS6").collect(Collectors.toList());
                    JSONArray skuPicJSONArray = JSONArray.parseArray(JSON.toJSONString(skuPicList));
                    PureImages skuPureImages = new PureImages();
                    skuPureImages.setProductId(id).setEan13(skuEan13).setImages(skuPicJSONArray.toJSONString());
                    pureImageList.add(skuPureImages);
                }
            }
        }
        return pureImageList;
    }
}
